/**
 * @FileName: OssUtils.java
 * @Author
 * @Description:
 * @Date 2016年4月11日 下午7:19:59
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.util;

import java.io.File;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

public class OssUtils{
    private static final String OSS_PROPERTIES = "oss.properties";

    public static UploadResult upload(File file, String fileName){
        UploadResult result;
        Prop prop = PropKit.use(OSS_PROPERTIES);
        OSSClient client = getOssClient(prop);
        try{
            PutObjectResult putResult = client.putObject(prop.get("bucket"), prop.get("appDir") + "/" + fileName, file);
            result = new UploadResult(putResult.getETag(), prop.get("ossUrlPrefix") + fileName);
        }
        finally{
            client.shutdown();
        }
        return result;
    }

    private static OSSClient getOssClient(Prop prop){
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(prop.getInt("connectionTimeout"));
        conf.setMaxErrorRetry(prop.getInt("maxErrorRetry"));
        conf.setSocketTimeout(prop.getInt("socketTimeout"));
        if(!StrKit.isBlank(prop.get("proxy"))){
            conf.setProxyHost(prop.get("proxy"));
            conf.setProxyPort(prop.getInt("proxyPort", 80));
        }
        OSSClient client1 = new OSSClient(prop.get("endpoint"), prop.get("accessKeyId"), prop.get("accessKeySecret"),
                conf);
        return client1;
    }

    public static class UploadResult{
        public String digest;
        public String url;

        public UploadResult(String eTag, String fileUrl){
            this.digest = eTag;
            this.url = fileUrl;
        }

        @Override
        public String toString(){
            return "UploadResult [digest=" + digest + ", url=" + url + "]";
        }

    }
}
